﻿
namespace Mulala.Cavan.Core.Settings
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Diagnostics.Contracts;
    using System.IO;
    using System.Linq;
    using Spring.Context;
    using Spring.Context.Support;
    using Mulala.Cavan.Core.Extension;

    /// <summary>
    ///     Provides the 'Configuration' based on the Project.config file
    /// </summary>
    public class Global
    {
        #region memebers
        static readonly Global Instance;

        IBaseSettings _defaultSettings;
        IBaseSettingsProvider _provider;
        #endregion memebers

        #region constructor
        /// <summary>
        ///     Singleton isntantiation
        /// </summary>
        static Global()
        {
            Instance = new Global();
        }

        /// <summary>
        ///     Initialize infrastructure for settings reading
        /// </summary>
        protected Global()
        {
        }
        #endregion constructor

        #region public IBaseSettings
        /// <summary>
        ///     Global application Settings
        /// </summary>
        public static IBaseSettings Settings
        {
            get
            {
                Instance.Initialize();
                if (Instance._provider.Is())
                {
                    return Instance._provider.BaseSettings;
                }
                return Instance._defaultSettings;
            }

        }
        #endregion public IBaseSettings

        #region protected Provider
        protected static IBaseSettingsProvider BaseProvider
        {
            get 
            {
                Instance.Initialize();
                return Instance._provider; 
            }
        }
        #endregion protected Provider

        #region init
        /// <summary>
        ///     IBaseSettingsProvider is instantiated
        /// </summary>
        void Initialize()
        {
            if (_provider.Is())
            {
                return;
            }
            IApplicationContext ctx = ContextRegistry.GetContext();
            _provider = ctx.GetObject("ProjectSettingsProvider") as IBaseSettingsProvider;

            _defaultSettings = ctx.GetObject("BasicSettings") as IBaseSettings;
        }
        #endregion init
    }
}